package com.qilu.pe.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.PayResult;
import com.qilu.pe.dao.bean.Order;
import com.qilu.pe.dao.bean.UPayInfo;
import com.qilu.pe.dao.bean.WxPayInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.PeUtil;
import com.qilu.pe.ui.activity.OrderDetailActivity;
import com.qilu.pe.ui.activity.PaySuccessActivity;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 我的订单fragment
public class MyOrder1Fragment extends BaseFragment {
    private RecyclerView rcv_list;// 我的订单列表
    private TextView empty_view;

    private MyOrderListAdapter adapter;
    private List<Order> orderList = new ArrayList<>();
    private String type = "";

    private String orderNum;// 订单号

    IWXAPI msgApi;

    public MyOrder1Fragment() {

    }

    public static MyOrder1Fragment newInstance(String type) {
        MyOrder1Fragment fragment = new MyOrder1Fragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getString("type");
        adapter = new MyOrderListAdapter(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_my_order1, container, false);
        rcv_list = v.findViewById(R.id.rcv_list);
        empty_view = v.findViewById(R.id.empty_view);

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);
        adapter.setDataList(orderList);

        hideProgress();
        reqMyOrderList();
        showProgress();

        alert = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();

        msgApi = WXAPIFactory.createWXAPI(getActivity(), null);
        msgApi.registerApp(Config.WX_APP_ID);

        return v;
    }

    private Disposable reqMyOrderList() {
        return APIRetrofit.getDefault().reqMyOrderList(Global.HEADER, type, 1, 999999)
                .compose(RxUtil.<BaseResult2<List<Order>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Order>>>() {
                    @Override
                    public void accept(BaseResult2<List<Order>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        orderList = listBaseResult2.getData();
                        adapter.setDataList(orderList);

                        if (isDataEmpty(orderList)) {
                            empty_view.setVisibility(View.VISIBLE);
                        } else {
                            empty_view.setVisibility(View.GONE);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        empty_view.setVisibility(View.VISIBLE);
                    }
                });
    }

    private class MyOrderListAdapter extends ListBaseAdapter<Order> {

        public MyOrderListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_order_list_mine_fragment;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            RelativeLayout rl_item = holder.getView(R.id.rl_item);
            TextView tv_code = holder.getView(R.id.tv_code);
            TextView tv_status = holder.getView(R.id.tv_status);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_item_num = holder.getView(R.id.tv_item_num);
            TextView tv_money = holder.getView(R.id.tv_money);
            TextView tv_date = holder.getView(R.id.tv_date);
            TextView tv_modify = holder.getView(R.id.tv_modify);// 修改订单
            TextView tv_pay = holder.getView(R.id.tv_pay);// 去付款
            TextView tv_cancel_refund = holder.getView(R.id.tv_cancel_refund);// 取消退款
            TextView tv_detail = holder.getView(R.id.tv_detail);// 查看详情

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) rl_item.getLayoutParams();

            if (position == 0) {
                params.topMargin = SizeUtils.dp2px(12);
                params.bottomMargin = SizeUtils.dp2px(6);
            } else if (position == mDataList.size() - 1) {
                params.topMargin = SizeUtils.dp2px(6);
                params.bottomMargin = SizeUtils.dp2px(12);
            } else {
                params.topMargin = SizeUtils.dp2px(6);
                params.bottomMargin = SizeUtils.dp2px(6);
            }

            final Order o = mDataList.get(position);

            tv_code.setText("订单编号:" + o.getOrder_num());
            final String status = PeUtil.getOrderStatus(o.getType());
            tv_status.setText(status);
            tv_name.setText(o.getName());
            tv_item_num.setText("共" + o.getCount() + "个检测项目");
            tv_money.setText("合计:¥" + o.getPrice());
            tv_date.setText("下单日期:" + o.getTime());

            // 订单状态 1 待付款,2 申请退款,3 订单取消,4 已退款,5 未接单,6 运输中,7 检验中,8 已出报告
            if (TextUtils.equals("1", o.getType())) {// 待付款
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.VISIBLE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("2", o.getType())) {// 申请退款
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("3", o.getType())) {// 订单取消
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("4", o.getType())) {// 已退款
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("5", o.getType())) {// 未接单
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("6", o.getType())) {// 运输中
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("7", o.getType())) {// 检验中
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("8", o.getType())) {// 已出报告
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else {
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            }

            tv_detail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", status);
                    bundle.putString("orderId", o.getId());
                    bundle.putString("orderType", o.getType());
                    startActivity(OrderDetailActivity.class, bundle);
                }
            });
            tv_pay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    orderNum = o.getOrder_num();
                    showDialog();
                }
            });
        }
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;
    String payType = "2";// 支付方式 1 微信,2 支付宝,3 银联支付,4 余额支付

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(getActivity(), R.layout.layout_alert_choose_pay_type, null);

        final RadioButton cb_ali = alert_view.findViewById(R.id.cb_ali);
        final RadioButton cb_wx = alert_view.findViewById(R.id.cb_wx);
        final RadioButton cb_union = alert_view.findViewById(R.id.cb_union);
        final RadioButton cb_balance = alert_view.findViewById(R.id.cb_balance);
        final TextView tv_balance0 = alert_view.findViewById(R.id.tv_balance0);// 显示余额数量

        RelativeLayout rl_ali = alert_view.findViewById(R.id.rl_ali);
        RelativeLayout rl_wechat = alert_view.findViewById(R.id.rl_wechat);
        RelativeLayout rl_union_pay = alert_view.findViewById(R.id.rl_union_pay);
        RelativeLayout rl_balance = alert_view.findViewById(R.id.rl_balance);

        tv_balance0.setText("余额支付 (¥" + Global.ORG_BALANCE + ")");

        rl_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_union_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        cb_union.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        rl_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });
        cb_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_ali.isChecked()) {
                    payType = "2";
                } else if (cb_wx.isChecked()) {
                    payType = "1";
                } else if (cb_union.isChecked()) {
                    payType = "3";
                } else if (cb_balance.isChecked()) {
                    payType = "4";
                }
                if (cb_ali.isChecked()) {// 支付宝
                    hideProgress();
                    reqAliPayInfo();
                    showProgress();
                } else if (cb_wx.isChecked()) {// 微信
                    hideProgress();
                    reqWxPayInfo();
                    showProgress();
                } else if (cb_union.isChecked()) {// 银联
                    hideProgress();
                    reqUPayPayInfo();
                    showProgress();
                } else if (cb_balance.isChecked()) {
                    hideProgress();
                    reqBalancePayInfo();
                    showProgress();
                }
                alert.dismiss();
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, getActivity());
    }

    private Disposable reqBalancePayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayBalance(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            startActivity(PaySuccessActivity.class);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_balance = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqUPayPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayUpay(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2<UPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<UPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            uPay(baseResult2.getData().getTn());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_upay = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqWxPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayWx(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2<WxPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<WxPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            wxPay(baseResult2);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_wx = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取微信支付信息错误");
                    }
                });
    }

    private Disposable reqAliPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayAli(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            String orderInfo = (String) baseResult2.getData();
                            aliPay(orderInfo);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_ali = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 调起银联支付
    private void uPay(String tn) {
        // “00” – 银联正式环境
        // “01” – 银联测试环境，该环境中不发生真实交易
        String serverMode = "01";
        UPPayAssistEx.startPay(Arad.app, null, null, tn, serverMode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            //显示支付结果
            ToastUtils.showShort("银联支付成功");
            // 结果为成功时，建议去商户后台查询一下再展示成功
        } else if (str.equalsIgnoreCase("fail")) {
            ToastUtils.showShort("银联支付失败");
        } else if (str.equalsIgnoreCase("cancel")) {
            ToastUtils.showShort("您取消了银联支付");
        }
    }

    // 调起微信支付
    private void wxPay(BaseResult2<WxPayInfo> baseResult2) {
        WxPayInfo wxPayInfo = baseResult2.getData();
        PayReq request = new PayReq();
        request.appId = wxPayInfo.getAppid();
        request.partnerId = wxPayInfo.getPartnerid();
        request.prepayId = wxPayInfo.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayInfo.getNoncestr();
        request.timeStamp = wxPayInfo.getTimestamp();
        request.sign = wxPayInfo.getSign();
        msgApi.sendReq(request);
    }

    // 调起支付宝支付
    private void aliPay(final String orderInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 20100851;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @SuppressWarnings("all")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //返回码，标识支付状态，含义如下：9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错
            if (msg.what == 20100851) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String payStatus = payResult.getResultStatus();
                if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付成功");
                    paySuc();

                } else if (TextUtils.equals(payStatus, "6001")) {
                    ToastUtils.showShort("取消支付");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付失败");
                }
            }
        }
    };

    private void paySuc() {
        startActivity(PaySuccessActivity.class);
    }
}